package com.wlw.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wlw.vo.BaseRespMessage;
import com.wlw.vo.P0002;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 
 * @Description netty 客户端处理
 * @author mHuang
 * @date 2015年7月16日 下午3:40:09 
 * @version V1.0.0
 */
@Sharable
public class NettyClientHandler extends  SimpleChannelInboundHandler<BaseRespMessage>{

	private static Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
	/**
	 * 
	 * Description  链接成功后执行..
	 * @param ctx
	 * @throws Exception 
	 * @see io.netty.channel.ChannelHandlerAdapter#channelActive(io.netty.channel.ChannelHandlerContext)
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().id().asLongText());
		System.out.println("client connection success");
//		P0100 login = new P0100();
//		ctx.writeAndFlush(login);
	}

	/**
	 * 
	 * Description 客户端异常
	 * @param ctx
	 * @param cause
	 * @throws Exception 
	 * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext, java.lang.Throwable)
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		try {
			super.exceptionCaught(ctx, cause);
		} catch (Exception e) {
			logger.info("client exception ....关闭连接");
			ctx.close();
		}
	}
	
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof IdleStateEvent){
			IdleStateEvent event = (IdleStateEvent)evt;
			if(event.state() == IdleState.READER_IDLE){
				logger.info("读取数据超时~~");
//				ctx.close();
			}else if(event.state() == IdleState.WRITER_IDLE){
				logger.info("写入超时、发送心跳包！");
				//写的心跳数据
				P0002 heart = new P0002();
//				heart.setHeader(new HeaderMessage(2, 0, 16, 0));
				ctx.writeAndFlush(heart);
			}
		}
		super.userEventTriggered(ctx, evt);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, BaseRespMessage msg) throws Exception {
		System.out.println(msg.getMsgId()+"----"+msg.getResult());
	}	
}
